package com.github.ghsea.scheduler.zkclient;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class ChildrenChangedListener implements PathChildrenCacheListener {

	private Logger log = LoggerFactory.getLogger(ChildrenChangedListener.class);

	private Serializer serializer;

	@Override
	public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
		String path = event.getData().getPath();
		switch (event.getType()) {

		// watched() monitor for one more time
		case CHILD_ADDED: {
			ChildData data = event.getData();
			notifyChildAdded(event.getData().getPath(),serializer.deserialize(data.getData()));
			break;
		}

		case CHILD_UPDATED: {
			log.debug("Node changed:{}", path);
			// System.out.println("Node changed: " +
			// ZKPaths.getNodeFromPath(event.getData().getPath()));
			ChildData data = event.getData();
			notifyChildUpdated(data.getPath(), data.getStat(), serializer.deserialize(data.getData()));
			break;
		}
		case CHILD_REMOVED: {
			// List<String> children = client.getChildren().watched().forPath(path);
			notifyChildRemoved(event.getData().getPath());
			break;
		}
		default:
			// do nothing
		}
	}

	public abstract void notifyChildAdded(String childAdded,Object data);

	public abstract void notifyChildRemoved(String childRemoved);

	public abstract void notifyChildUpdated(String childUpdated, Stat stat, Object data);

	protected void setSerializer(Serializer serializer) {
		this.serializer = serializer;
	}

}
